<template>
  <!-- 新增联防队员 -->
  <view>
    <view v-if="!visibleCamera">
      <view class="newJointDefense">
        <view class="content">
          <view class="content-item">
            <view class="title">身份信息</view>
            <view><u-line></u-line></view>
            <u-cell-group :border="false">
              <!-- <u-cell :titleStyle="titleStyle" title="证件照片" :border="false">
              </u-cell> -->
              <!-- <view class="upload-view">
                <u-upload :fileList="fileList3" @afterRead="afterReadThree" @delete="deletePic(3)" name="file" :maxCount="1"
                  width="310" height="180" :delIconCenter="true" :delIconSize="40">
                  <image :src="baseImgUrl + 'card_3.png'" style="width: 640rpx; height: 360rpx"></image>
                </u-upload>
              </view> -->
              <!-- 身份证号 -->
              <view class="idcard-style">
                <u-cell :titleStyle="titleStyle" title="身份证号" v-if="paiNew">
                  <text slot="icon" class="required">*</text>
                  <u-input type="idcard" v-model="form.idCard" data-type="workPerson" placeholder="请输入" slot="value"
                    fontSize="14" placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="18"
                    :required="true" @blur="idCardHandle"></u-input>
                  <view class="scan-wrapper" @click="handleCamera" slot="right-icon">
                    <image src="/static/icons/scan.png" class="scan-img"></image>
                  </view>
                </u-cell>
              </view>
              <!-- 姓名 -->
              <u-cell :titleStyle="titleStyle" title="姓名">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.personName" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                  placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell>

              <!-- 户籍地址 -->
              <!--  <u-cell :titleStyle="titleStyle" title="户籍地址">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.residenceDetail" data-type="workPerson" placeholder="请输入" slot="value"
                  fontSize="14" placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell> -->

              <!-- 现居地址 -->
              <!-- <u-cell :titleStyle="titleStyle" title="现居地址">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.addressDetail" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                  placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell> -->

              <!-- 联系方式 -->
              <u-cell :titleStyle="titleStyle" title="联系方式">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.mobile" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                  placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30" :required="true"
                  @blur="phoneHandle"></u-input>
              </u-cell>

              <u-cell :titleStyle="titleStyle" title="人脸照片" :border="false" v-if="paiNew">
                <text slot="icon" class="required">*</text>
              </u-cell>
              <view class="upload-view" v-if="paiNew">
                <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic(1)" name="file" :maxCount="1"
                  width="110" height="90">
                  <image :src="baseImgUrl + 'upload-icon2.png'" style="width: 220rpx; height: 180rpx"></image>
                </u-upload>
              </view>

              <view class="title">基本信息</view>
              <u-cell :titleStyle="titleStyle" title="政治面貌">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.politicalOutlook" data-type="workPerson" placeholder="请输入" slot="value"
                  fontSize="14" placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell>

              <u-cell :titleStyle="titleStyle" title="民族">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.race" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                  placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell>

              <u-cell :titleStyle="titleStyle" title="籍贯">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.nativePlace" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                  placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell>

              <u-cell :titleStyle="titleStyle" title="身高(cm)">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.height" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                  placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="5" :required="true"
                  @blur="heightHandle" :formatter="heightFormatter"></u-input>
              </u-cell>

              <u-cell :titleStyle="titleStyle" title="健康状况">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.healthStatus" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                  placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell>

              <u-cell :titleStyle="titleStyle" title="婚姻状况">
                <u-input v-model="form.maritalStatus" data-type="workPerson" placeholder="请输入" slot="value"
                  fontSize="14" placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell>

              <u-cell :titleStyle="titleStyle" title="学历">
                <u-input v-model="form.education" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                  placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell>

              <u-cell :titleStyle="titleStyle" title="专业">
                <u-input v-model="form.speciality" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                  placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell>

              <view class="title">工作信息</view>
              <u-cell :titleStyle="titleStyle" title="培训机构">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.trainingInstitutions" data-type="workPerson" placeholder="请输入" slot="value"
                  fontSize="14" placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell>

              <u-cell :titleStyle="titleStyle" title="培训开始时间" clickable isLink :rightIconStyle="rightIconStyle"
                @click="cellTimeClick('trainingStartTimeName')">
                <text slot="icon" class="required">*</text>
                <view slot="value" :class="
                    form.trainingStartTimeName ? 'cell-noEmpty' : 'cell-empty'
                  ">
                  {{ form.trainingStartTimeName || "请选择" }}
                </view>
              </u-cell>
              <u-cell :titleStyle="titleStyle" title="培训结束时间" clickable isLink :rightIconStyle="rightIconStyle"
                data-type="trainingEndTimeName" @click="cellTimeClick('trainingEndTimeName')">
                <text slot="icon" class="required">*</text>
                <view slot="value" :class="form.trainingEndTimeName ? 'cell-noEmpty' : 'cell-empty'">
                  {{ form.trainingEndTimeName || "请选择" }}
                </view>
              </u-cell>

              <u-cell :titleStyle="titleStyle" title="执勤编号">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.dutyNumber" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                  placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell>

              <u-cell :titleStyle="titleStyle" title="发证机关">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.issuingUnit" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                  placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell>

              <u-cell :titleStyle="titleStyle" title="工作单位">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.workUnit" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                  placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                  :required="true"></u-input>
              </u-cell>

              <u-cell :titleStyle="titleStyle" title="入职时间" clickable isLink :rightIconStyle="rightIconStyle"
                @click="cellTimeClick('employmentTimeName')">
                <text slot="icon" class="required">*</text>
                <view slot="value" :class="form.employmentTimeName ? 'cell-noEmpty' : 'cell-empty'">
                  {{ form.employmentTimeName || "请选择" }}
                </view>
              </u-cell>
            </u-cell-group>
          </view>
        </view>

        <view class="btns">
          <button class="reset-btn lt cancelBtn" type="primary" @click="resethandle">
            取消
          </button>
          <button class="submit-btn" type="primary" @click="submitHandle">
            保存
          </button>
        </view>

        <u-picker :show="pickerShow" :columns="columns" :keyName="keyName" @confirm="showConfirm" @close="pickerClose"
          @cancel="pickerCancel" :closeOnClickOverlay="true"></u-picker>

        <!-- 时间选择器 -->
        <u-datetime-picker ref="datetimePicker" :show="datetimeShow" v-model="timeValue" mode="date"
          :formatter="formatter" :minDate="minDate" :maxDate="maxDate" @close="pickerTimeClose"
          @cancel="pickerTimeClose(1)" @confirm="showTimeConfirm" :closeOnClickOverlay="true"></u-datetime-picker>
      </view>
    </view>
    <yy-photo-mask :visible.sync="visibleCamera" :baseImgUrl="baseImgUrl" :clientId="clientId"
      :clientSecret="clientSecret" @generateFilePath="onGenerateFilePath" @parsedSuccess="onParsedSuccess">
    </yy-photo-mask>
  </view>
</template>

<script>
  import {
    jointDefencePersonAdd
  } from "@/api/home.js";
  import {
    findEnableDictItemsbyCode
  } from "@/api/api.js";
  import {
    Toast,
    navBack,
    checkIDCard,
    formatters,
    dayTurnTime,
    getBase64Two,
    uniTrim,
    useNetWork,
    isLoading,
    positiveNumber,
    getHeader,
    heightFormatter,
    uploadFile
  } from "@/utils/util.js";
  import mixin from "@/utils/mixin.js";

  export default {
    name: "newJointDefense",
    mixins: [mixin],
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        baseURL: this.$baseURL,
        clientId: this.$clientId,
        clientSecret: this.$clientSecret,
        paiNew: uni.getStorageSync("paiNew"),
        options: {},
        form: {},
        errorType: ["none"],
        fileList: [],
        fileList3: [],
        visibleCamera: false
      };
    },
    onLoad(options) {
      this.options = options;
    },
    methods: {
      heightFormatter,
      handleCamera() {
        this.visibleCamera = true;
      },
      onParsedSuccess({
        userName,
        idcard,
        domicileAddress,
        words_result
      }) {
        this.$set(
          this.form,
          "personName",
          userName
        );
        this.$set(
          this.form,
          "idCard",
          idcard
        );
        // this.$set(
        //   this.form,
        //   "residenceDetail",
        //   domicileAddress
        // );
      },
      onGenerateFilePath(file) {
        this.uploadCard(file)
      },
      phoneHandle() {
        if (this.form.mobile && !this.$u.test.mobile(this.form.mobile)) {
          Toast("请输入正确的手机号");
          return;
        }
      },
      idCardHandle() {
        let idCardFlag = checkIDCard(this.form.idCard);
        if (!idCardFlag) {
          Toast("请输入正确的证件号码");
          return;
        }
      },
      heightHandle() {
        let height = positiveNumber(this.form.height);
        if (!height) {
          Toast("请输入正确的身高");
          return;
        }
      },
      formatter(type, value) {
        if (type === "year") {
          return `${value}年`;
        }
        if (type === "month") {
          return `${value}月`;
        }
        if (type === "day") {
          return `${value}日`;
        }
        return value;
      },
      cellTimeClick(e) {
        this.cellType = e;
        var minDateNum = +new Date(); //获取当前时间的毫秒数

        switch (this.cellType) {
          case "trainingStartTimeName":
            this.minDate = new Date(1971, 0, 1).getTime();
            this.maxDate = minDateNum;

            this.$nextTick(() => {
              this.timeValue = this.maxDate;
            });
            break;
          case "trainingEndTimeName":
            this.minDate = dayTurnTime(this.form.trainingStartTimeName);
            this.maxDate = minDateNum;

            this.$nextTick(() => {
              this.timeValue = this.minDate;
            });
            break;
          case "employmentTimeName":
            this.minDate = new Date(1971, 0, 1).getTime();
            this.maxDate = minDateNum;

            this.$nextTick(() => {
              this.timeValue = this.maxDate;
            });
            break;
          default:
            break;
        }

        if (
          this.cellType == "trainingEndTimeName" &&
          !this.form.trainingStartTimeName
        ) {
          Toast("请选择培训开始时间");
          return false;
        }

        setTimeout(() => {
          this.datetimeShow = true;
        }, 100);
      },
      pickerTimeClose(e) {
        if (e) {
          switch (this.cellType) {
            case "trainingStartTimeName":
              this.form.trainingStartTime = "";
              this.form.trainingStartTimeName = "";
              break;
            case "trainingEndTimeName":
              this.form.trainingEndTime = "";
              this.form.trainingEndTimeName = "";
              break;
            case "employmentTimeName":
              this.form.employmentTime = "";
              this.form.employmentTimeName = "";
              break;
            default:
              break;
          }
        }
        this.datetimeShow = false;
      },
      /* 时间选择器 确定 */
      showTimeConfirm(e) {
        let arr = e.value;
        if (arr) {
          switch (this.cellType) {
            case "trainingStartTimeName":
              this.form.trainingStartTimeName = formatters(arr, "YY/MM/DD");
              this.form.trainingStartTime = dayTurnTime(
                this.form.trainingStartTimeName
              );

              this.form.trainingEndTime = "";
              this.form.trainingEndTimeName = "";
              break;
            case "trainingEndTimeName":
              this.form.trainingEndTimeName = formatters(arr, "YY/MM/DD");
              this.form.trainingEndTime = dayTurnTime(
                this.form.trainingEndTimeName
              );
              break;
            case "employmentTimeName":
              this.form.employmentTimeName = formatters(arr, "YY/MM/DD");
              this.form.employmentTime = dayTurnTime(
                this.form.employmentTimeName
              );
              break;
            default:
              break;
          }
        }
        this.datetimeShow = false;
      },
      afterRead(info) {
        useNetWork(); // 判断是否有网络
        isLoading();
        let _this = this;

        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: info.file.url,
            name: "file",
            formData: {
              type: 6,
            },
          })
          .then((res) => {
            isLoading(false);
            let {
              fullPath,
              halfPath
            } = res.result;
            _this.fileList.push({
              url: fullPath
            });
            _this.form.personImage = halfPath;
          })
          .finally(() => {
            isLoading(false);
          })
      },
      deletePic(num) {
        if (num == 1) {
          this.fileList = [];
          this.form.personImage = "";
        }

        if (num == 3) {
          this.fileList3 = [];
          this.form.idCardImage = "";
        }
      },
      afterReadThree(info) {
        let _this = this;

        uni.request({
          url: "https://aip.baidubce.com/oauth/2.0/token",
          method: "GET",
          data: {
            grant_type: "client_credentials",
            client_id: _this.clientId,
            client_secret: _this.clientSecret,
          },
          success(res) {
            _this.base64Handle(res.data.access_token, info);
          },
        });
      },
      base64Handle(token, info) {
        let _this = this;

        getBase64Two(info.file.url)
          .then((res) => {
            return res;
          })
          .then((res) => {
            uni.request({
              url: `https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=${token}`,
              method: "POST",
              header: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
              data: {
                id_card_side: "front",
                image: res,
              },
              success(resbai) {
                let {
                  statusCode,
                  data
                } = resbai;
                if (statusCode == 200 && data.words_result["姓名"]) {
                  _this.$set(
                    _this.form,
                    "personName",
                    data.words_result.姓名.words
                  );
                  _this.$set(
                    _this.form,
                    "idCard",
                    data.words_result.公民身份号码.words
                  );
                  // _this.$set(
                  //   _this.form,
                  //   "residenceDetail",
                  //   data.words_result.住址.words
                  // );
                  _this.uploadCard(info.file.url);
                  return;
                }

                Toast("未识别");
                _this.uploadCard(info.file.url);
                // Toast("请上传正确的身份证证件照片");
              },
            });
          });
      },
      uploadCard(fileurl) {
        useNetWork(); // 判断是否有网络
        isLoading();

        let _this = this;
        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: fileurl,
            name: "file",
            formData: {
              type: 20,
            },
          })
          .then((res) => {
            isLoading(false);
            let {
              fullPath,
              halfPath
            } = res.result;
            _this.fileList3.push({
              url: fullPath
            });
            _this.form.idCardImage = halfPath;
          })
          .finally(() => {
            isLoading(false);
          })
      },
      resethandle() {
        uni.navigateBack();
      },
      submitHandle() {
        let {
          idCardImage,
          idCard,
          // residenceDetail,
          addressDetail,
          personImage,
          personName,
          mobile,
          politicalOutlook,
          race,
          nativePlace,
          height,
          healthStatus,
          trainingInstitutions,
          trainingStartTime,
          trainingEndTime,
          dutyNumber,
          issuingUnit,
          workUnit,
          employmentTime,
        } = this.form;

        if (!idCardImage) {
          Toast("请上传证件照片");
          return;
        }

        if (!personName || !uniTrim(personName)) {
          Toast("请输入姓名");
          return;
        }

        if (!idCard || !uniTrim(idCard)) {
          Toast("请输入身份证号");
          return;
        }

        let idCardFlag = checkIDCard(this.form.idCard);
        if (!idCardFlag) {
          Toast("请输入正确的证件号码");
          return;
        }

        // if (!residenceDetail || !uniTrim(residenceDetail)) {
        //   Toast("请输入户籍地址");
        //   return;
        // }

        // if (!addressDetail || !uniTrim(addressDetail)) {
        //   Toast("请输入现居地址");
        //   return;
        // }

        if (!mobile || !uniTrim(mobile)) {
          Toast("请输入联系方式");
          return;
        }

        if (mobile && !this.$u.test.mobile(mobile)) {
          Toast("请输入正确的手机号");
          return;
        }

        if (!personImage) {
          Toast("请上传人脸头像");
          return;
        }

        if (!politicalOutlook || !uniTrim(politicalOutlook)) {
          Toast("请输入政治面貌");
          return;
        }

        if (!race || !uniTrim(race)) {
          Toast("请输入民族");
          return;
        }

        if (!nativePlace || !uniTrim(nativePlace)) {
          Toast("请输入籍贯");
          return;
        }

        if (!height || !uniTrim(height)) {
          Toast("请输入身高");
          return;
        }

        let heightFlag = positiveNumber(this.form.height);
        if (!heightFlag) {
          Toast("请输入正确的身高");
          return;
        }

        if (!healthStatus || !uniTrim(healthStatus)) {
          Toast("请输入健康状况");
          return;
        }

        if (!trainingInstitutions || !uniTrim(trainingInstitutions)) {
          Toast("请输入培训机构");
          return;
        }

        if (!trainingStartTime) {
          Toast("请选择培训开始时间");
          return;
        }

        if (!trainingEndTime) {
          Toast("请选择培训结束时间");
          return;
        }

        if (!dutyNumber || !uniTrim(dutyNumber)) {
          Toast("请输入执勤编号");
          return;
        }

        if (!issuingUnit || !uniTrim(issuingUnit)) {
          Toast("请输入发证机关");
          return;
        }

        if (!workUnit || !uniTrim(workUnit)) {
          Toast("请输入工作单位");
          return;
        }

        if (!employmentTime || !uniTrim(employmentTime)) {
          Toast("请选择入职时间");
          return;
        }

        let data = {
          companyMessageId: this.options.companyId,
          ...this.form,
        };

        jointDefencePersonAdd(data).then((res) => {
          if (res.code == 200) {
            Toast("添加成功");
            uni.setStorageSync("defensiveLineman", true);
            navBack();
            return;
          }

          Toast(res.message);
        });
      },
    },
  };
</script>

<style lang="scss">
  .newJointDefense {
    flex: 1;
    background-color: #f9f9f9;

    .content {
      margin: 0 auto;
      margin-top: 20rpx;
      margin-bottom: 20rpx;
      border-radius: 8rpx;
      width: calc(100% - 35rpx);
      height: calc(100vh - 84px);
      overflow-y: auto;

      .content-item {
        padding: 25rpx;
        background: #fff;

        .title {
          padding: 20rpx 0;
          font-size: 36rpx;
          font-weight: bold;
        }

        .upload-view {
          padding-left: 30rpx;
        }
      }

      .required {
        position: absolute;
        left: 20rpx;
      }
    }

    .u-input__content {
      width: 450rpx;
    }

    .scan-wrapper {
      padding: 10rpx;

      .scan-img {
        width: 30rpx;
        height: 27.73rpx;
      }
    }

    .idcard-style {
      /deep/ .u-cell__body {
        padding-right: 0;
      }

      /deep/ .u-input__content__field-wrapper__field {
        padding-right: 8rpx !important;
      }
    }
  }
</style>